<?php
/**
 * @author spenceryg
 * @date 2023/6/23
 * @time 10:25 下午
 * @focus love & life
 */


namespace app\api1\controller;


use app\common\model\GptToken;
use GuzzleHttp\Client;
use hg\apidoc\annotation as Apidoc;

class Embedding extends \app\BaseController
{

    /**
     * train
     * @Apidoc\Title("训练")
     * @Apidoc\Query("id", type="int", default="1", desc="文件id")
     */
    public function train($id)
    {
        if(!$id) {
            $id = input('id');
        }
        $robotFile = \app\common\model\RobotFiles::find($id);
        $gptToken = GptToken::order('update_time desc')->find();
        $gptToken->force(true)->save();
        $openai_api_key = $gptToken['token'];
        $json = [];
        $json['openai_api_key'] = $openai_api_key;
        $json['filename'] = $robotFile['name'];
        $json['file_id'] = $robotFile['id'];
        $json['collection_name'] = 'collection_' .  $robotFile['robot_id'];
        $json['persist_directory'] = 'file_' . $robotFile['robot_id'];

        $client = new \GuzzleHttp\Client(
            [
                'base_uri' => config('transfer.transit_address'),
                'timeout' => 80,
            ]
        );


        try {
            $res = $client->request('post', '/embedding', [
                'json' => $json,
            ]);

            $body = $res->getBody()->getContents();
            $data = json_decode($body, true);
            $robotFile->is_train = 1;
            $robotFile->number_of_documents = $data['length'];
            $robotFile->save();
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return error($msg, []);
        }
        return success('训练成功', $data);

    }

    /**
     * db_status
     * @Apidoc\Title("db状态")
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function db_status()
    {
        $client = new Client([
            'base_uri' =>config('transfer.transit_address'),
            'timeout' => 80,
        ]);
        $res = $client->request('get', '/db_status?persist_directory=file_' . input('robot_id'));
        $body = $res->getBody()->getContents();
        $data = json_decode($body, true);
        dump($data);
    }



}
